<template>
  <el-dialog v-model="model" :align-center="props.alineCenter" :draggable="props.draggable" :overflow="props.overflow"
    :show-close="props.showClose" :destroy-on-close="destroyDialog" :center="props.center" :modal="props.modal"
    :append-to-body="props.appendBody" :header="props.title" :width="props.width" :before-close="closeDialog"
    modal-class="dialog-class" class="dialog-style" :close-on-click-modal="props.clickBlankToClose">
    <!-- 自定义头部 -->
    <template #header="{ titleId, titleClass }">
      <div class="flex flex-row justify-between gap-4">
        <h4 :id="titleId" :class="titleClass">{{ props.title }}</h4>
      </div>
    </template>
    <!-- 自定义底部 -->
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
    </template>

    <!-- content -->
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px" class="password-form">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" autocomplete="username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" autocomplete="new-password" type="password" placeholder="请输入原密码" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
      </el-form-item>
    </el-form>


  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { editSubmitApi } from '@/utils/api.js';
import { ElMessage } from 'element-plus'
import { useStore } from '@/store/useState'
import { useRouter } from 'vue-router'
const store = useStore()
const router = useRouter()

const props = defineProps({
  appendBody: {
    type: Boolean,
    default: false,
  },
  width: {
    type: [String, Number],
    default: "600",
  },
  // 可通过 插槽自定义
  title: {
    type: String,
    default: "更改密码",
  },
  // 遮罩层
  modal: {
    type: Boolean,
    default: true,
  },
  // 关闭按钮显示状态
  showClose: {
    type: Boolean,
    default: true,
  },
  // 使对话框水平垂直居中
  alineCenter: {
    type: Boolean,
    default: true,
  },
  // 内容居中
  center: {
    type: Boolean,
    default: false,
  },
  // 关闭时销毁=== v-if
  destroyDialog: {
    type: Boolean,
    default: true,
  },
  // 拖拽
  draggable: {
    type: Boolean,
    default: false,
  },
  // 让拖拽范围超出可视区
  overflow: {
    type: Boolean,
    default: false,
  },
});
const ruleFormRef = ref(null);
const formData = reactive({
  username: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== formData.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
    return;
  }

  if (value.length < 8 || value.length > 16) {
    callback(new Error('密码长度必须在8-16位之间'));
    return;
  }

  let types = 0;
  if (/[A-Z]/.test(value)) types++; // 大写字母
  if (/[a-z]/.test(value)) types++; // 小写字母
  if (/[0-9]/.test(value)) types++; // 数字
  if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) types++; // 特殊符号

  if (types < 3) {
    callback(new Error('密码必须包含数字、大小写字母、特殊符号中的至少3种'));
    return;
  }

  callback();
};


const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          username: formData.username,
          oldPassword: formData.oldPassword,
          newPassword: formData.newPassword
        };

        await editSubmitApi(params);
        ElMessage.success('密码修改成功')
        onBack()
        closeDialog();
      } catch (error) {
        ElMessage.error(error.message || '密码修改失败');
      }
    }
  });
};
const onBack=()=>{
  store.deleteToken()
  router.push('/login')
}

const closeDialog = () => {
  formData.username = '';
  formData.oldPassword = '';
  formData.newPassword = '';
  formData.confirmPassword = '';
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  model.value = false;
};

const model = defineModel();

</script>
<style scoped>
.dialog-style {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dialog-style :deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.dialog-style :deep(.el-dialog__header) {
  background-color: #f8f9fa;
  padding: 16px 20px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

.dialog-style :deep(.el-dialog__body) {
  padding: 24px;
  background-color: #fff;
}

.dialog-style :deep(.el-dialog__footer) {
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.dialog-style :deep(.el-button) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.dialog-style :deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-style :deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.dialog-style :deep(.el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.password-form {
  max-width: 480px;
  margin: 0 auto;
}
</style>